package com.dayu.finecomm.protocol.pojo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

/**
 * 上传scada系统时候的封装类，具体参考GatewayReq、GatewayDataReq
 * 
 * @author Chenjiawei
 *
 *         2017年7月6日
 */
public class OpcTPacket extends TPacket {

	public VType type;
	public String device;
	public String code;
	public String tag;
	public Number value;
	public Long timestamp;

	public LinkedList<OpcTSensor> sensors;

	public OpcTPacket(VType type, String device, Long timestamp) {
		this(type, device, null, null, null, timestamp);
	}

	public OpcTPacket(VType type, String device, String code, String tag,
			Number value, Long timestamp) {
		this.type = type;
		this.device = device;
		this.code = code;
		this.tag = tag;
		this.value = value;
		this.timestamp = timestamp;
		this.sensors = new LinkedList<>();
	}

	@Override
	public String toString() {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		StringBuilder sb = new StringBuilder();

		sb.append(this.type.name());
		sb.append("{");
		sb.append(device);
		sb.append("}");

		boolean first = true;

		sb.append("{");

		for (OpcTSensor s : sensors) {

			Long ts = s.timestamp;

			if (ts == null) {
				ts = this.timestamp;
			}

			if (ts == null)
				continue;

			if (!first)
				sb.append('|');
			else
				first = false;

			sb.append(s.code);
			sb.append("#");
			sb.append(s.tag);
			sb.append("|");

			if (s.value instanceof Double || s.value instanceof Float) {
				sb.append(String.format("%.6f", s.value));
			} else {
				sb.append(s.value);
			}

			sb.append("|");
			sb.append(sdf.format(new Date(ts)));

		}
		sb.append("}");

		return sb.toString();
	}
}
